package br.com.sms.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.struts2.ServletActionContext;

import br.com.sms.dominio.Destinatario;
import br.com.sms.dto.EtiquetaDTO;
import br.com.sms.enuns.TIPOARQUIVO;

@SuppressWarnings("serial")
public class JasperAction extends Action{
	

	/** List to use as our JasperReports dataSource. */
    private List<Destinatario> myList;

    public String execute() throws Exception {

        Destinatario p1 = new Destinatario ("Patrick", "Lightbuddie");
        Destinatario p2 = new Destinatario ("Jason", "Carrora");
        Destinatario p3 = new Destinatario ("Alexandru", "Papesco");
        Destinatario p4 = new Destinatario ("Jay", "Boss");

        // Store people in our dataSource list (normally would come from database).
        myList = new ArrayList<Destinatario >();
        myList.add(p1);
        myList.add(p2);
        myList.add(p3);
        myList.add(p4);

        // Normally we would provide a pre-compiled .jrxml file
        // or check to make sure we don't compile on every request.
        try {
            JasperCompileManager.compileReportToFile(
                    "WebContent/WEB-INF/relatorios/etiquetas.jrxml",
                    "WebContent/WEB-INF/relatorios/etiquetas.jasper");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS;
    }
	
	
	public String gerarPDF(EtiquetaDTO etiquetaDTO) throws IOException {  
	    byte[] bytePDF = null;  
	    
	    try { 
	        bytePDF = JasperExportManager.exportReportToPdf(gerarConteudo(etiquetaDTO));
	        
	        //exibe o popup para salvar o pdf
	        writeBytesAsAttachedTextFile(bytePDF, "etiquetas", TIPOARQUIVO.PDF);
	        
	    } catch(JRException jrex) {
	    	System.out.println(jrex.getMessage());
	    	throw new IOException(jrex.getMessage());  
	    } catch (Exception e) {
	    	System.out.println(e.getMessage());
	    	throw new IOException(e.getMessage());
		} 
	    
	    return "success";  
	} 
	
	
	
	private JasperPrint gerarConteudo(EtiquetaDTO etiquetaDTO) throws JRException { 
		ServletContext servletContext = ServletActionContext.getServletContext(); 
		
		String pathRel = servletContext.getRealPath("/WEB-INF/relatorios/");
        
        Collection<Destinatario> listaDestinatarios = etiquetaDTO.getDestinatarios();
        myList = etiquetaDTO.getDestinatarios();
        JRBeanCollectionDataSource BCD = new JRBeanCollectionDataSource(listaDestinatarios);
        
		Map<String, Object> parametros = new HashMap<String, Object>();
		
		parametros.put("listaDestinatarios", BCD);
		parametros.put("CAMINHO_JASPERS", pathRel); 
        
        pathRel += "/etiquetas.jasper";
        
        return JasperFillManager.fillReport(pathRel, parametros, new JREmptyDataSource());   
	} 
	
	
	private static void writeBytesAsAttachedTextFile(byte[] bytes, String fileName, TIPOARQUIVO contentType) throws Exception {  
	      if (bytes == null)  
	         throw new Exception("Array de bytes nulo.");  
	  
	      if (fileName == null)  
	         throw new Exception("Nome do arquivo é nulo.");  
	        
	      HttpServletResponse response =  ServletActionContext.getResponse();
	      
	      switch(contentType){
	      	case PDF:
	      		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".pdf \";");
	      		break;
	      	case XLS:
	      		response.setContentType("application/vnd.ms-excel");  
			    response.setHeader("Content-disposition","attachment; filename="+fileName+".xls"); 
	      		break;
	      }
	      
	      response.setContentLength(bytes.length);  
	      ServletOutputStream ouputStream = response.getOutputStream();  
	      ouputStream.write(bytes, 0, bytes.length);  
	      ouputStream.flush();   
	      ouputStream.close();
   }



	public List<Destinatario> getMyList() {
		return myList;
	}

}
